<template>
  <div class="song-page" v-if="song.id">
    <div class="song-header">
      <div class="album-cover">
        <img :src="song.picUrl || defaultCover" :alt="song.name" @error="handleCoverError" />
      </div>
      <div class="song-info">
        <h1 class="song-name">{{ song.name }}</h1>
        <p class="song-singer">歌手：{{ song.singer }}</p>
        <p class="song-album" v-if="song.album">专辑：{{ song.album }}</p>
        <p class="song-duration">时长：{{ formatTime(song.duration) }}</p>
        <div class="actions">
          <el-button type="primary" @click="playSong(song)">
            <el-icon><VideoPlay /></el-icon> 播放
          </el-button>
          <el-button @click="addToPlaylist(song)">
            <el-icon><Plus /></el-icon> 添加到播放列表
          </el-button>
        </div>
      </div>
    </div>

    <div class="lyrics-section">
      <h2>歌词</h2>
      <div class="lyrics-container" ref="lyricsContainer">
        <div
          class="lyrics-content"
          :style="{ transform: `translateY(${-currentLyricIndex * 32 + 160}px)` }"
        >
          <div
            class="lyrics-line"
            :class="{ active: index === currentLyricIndex }"
            v-for="(line, index) in lyricsLines"
            :key="index"
          >
            {{ line.text }}
          </div>
        </div>
      </div>
    </div>
  </div>

  <div class="song-page" v-else>
    <el-empty description="歌曲信息加载中..." />
  </div>
</template>

<script>
import { ref, watch, onMounted, onUnmounted } from 'vue'
import { useRoute } from 'vue-router'
import { usePlayerStore } from '@/store/player'
import { ElMessage } from 'element-plus'
import { VideoPlay, Plus } from '@element-plus/icons-vue'
import defaultCoverImage from '@/assets/img/song-default.png'
import { getSongById } from '@/services/song'

export default {
  name: 'Song',
  components: {
    VideoPlay,
    Plus
  },
  setup() {
    const route = useRoute()
    const playerStore = usePlayerStore()

    const song = ref({})
    const defaultCover = defaultCoverImage
    const lyricsLines = ref([])
    const currentLyricIndex = ref(-1)
    const lyricsContainer = ref(null)
    const currentTime = ref(0)
    const timeUpdateInterval = ref(null)

    // 格式化时间
    const formatTime = (seconds) => {
      if (isNaN(seconds) || seconds === null) return '0:00'
      const mins = Math.floor(seconds / 60)
      const secs = Math.floor(seconds % 60)
      return `${mins}:${secs.toString().padStart(2, '0')}`
    }

    // 解析歌词
    const parseLyrics = (lyrics) => {
      if (!lyrics || typeof lyrics !== 'string') {
        return []
      }

      const lines = lyrics.split('\n')
      const parsedLyrics = []

      for (const line of lines) {
        // 跳过空行
        if (!line.trim()) continue

        // 匹配时间戳格式 [mm:ss.xx] 或 [mm:ss]
        const timeMatches = [...line.matchAll(/\[(\d{2}):(\d{2})(?:\.(\d{2,3}))?\]/g)]

        // 提取歌词文本（去掉所有时间戳）
        const text = line.replace(/\[\d{2}:\d{2}(?:\.\d{2,3})?\]/g, '').trim()

        // 如果没有文本内容，跳过这一行
        if (!text) continue

        // 处理可能包含多个时间戳的行（如歌词重复）
        if (timeMatches.length > 0) {
          for (const match of timeMatches) {
            const minutes = parseInt(match[1])
            const seconds = parseInt(match[2])
            // 处理毫秒部分，确保是正确的数值
            const milliseconds = match[3] ? parseInt(match[3].padEnd(3, '0').substring(0, 3)) : 0
            const time = minutes * 60 + seconds + milliseconds / 1000

            parsedLyrics.push({
              time: time,
              text: text
            })
          }
        } else {
          // 如果没有时间戳但有文本内容（如歌词信息行），添加一个特殊时间
          parsedLyrics.push({
            time: 0,
            text: text
          })
        }
      }

      // 按时间排序
      parsedLyrics.sort((a, b) => a.time - b.time)
      return parsedLyrics
    }

    // 更新当前歌词索引
    const updateCurrentLyric = () => {
      if (lyricsLines.value.length === 0) return

      // 查找当前时间对应的歌词
      let newIndex = -1
      for (let i = 0; i < lyricsLines.value.length; i++) {
        // 如果是最后一行歌词，或者下一歌词的时间大于当前时间
        if (i === lyricsLines.value.length - 1 || lyricsLines.value[i + 1].time > currentTime.value) {
          newIndex = i
          break
        }
      }

      // 只有在索引改变时才更新
      if (currentLyricIndex.value !== newIndex) {
        currentLyricIndex.value = newIndex
      }
    }

    // 获取歌曲详情
    const fetchSongDetail = async (id) => {
      try {
        const response = await getSongById(id)
        if (response.code === '1') {
          song.value = {
            id: response.data.songId || response.data.id,
            name: response.data.songName || response.data.name,
            singer: response.data.singerName || response.data.singer,
            album: response.data.songAlbum || response.data.album,
            duration: response.data.duration,
            picUrl: response.data.songPic || response.data.picUrl,
            lyric: response.data.songLyr || response.data.lyric,
            url: `/api/song/songOfId/${response.data.songId || response.data.id}`
          }

          // 解析歌词
          lyricsLines.value = parseLyrics(response.data.songLyr || response.data.lyric)
          currentLyricIndex.value = -1
        } else {
          ElMessage.error('获取歌曲详情失败: ' + (response.message || '未知错误'))
        }
      } catch (error) {
        ElMessage.error('获取歌曲详情失败: ' + error.message)
      }
    }

    // 播放歌曲
    const playSong = (song) => {
      playerStore.setCurrentSong(song)
      playerStore.isPlaying = true
    }

    // 添加到播放列表
    const addToPlaylist = (song) => {
      playerStore.addToPlaylist(song)
      ElMessage.success('已添加到播放列表')
    }

    // 处理封面图片错误
    const handleCoverError = (e) => {
      e.target.src = defaultCover
    }

    // 监听路由变化
    watch(
      () => route.params.id,
      (newId) => {
        if (newId) {
          fetchSongDetail(newId)
        }
      },
      { immediate: true }
    )

    // 监听播放时间变化
    const updateTime = () => {
      // 这里应该从播放器 store 获取当前播放时间
      const playerAudio = document.querySelector('.song-audio audio')
      if (playerAudio) {
        currentTime.value = playerAudio.currentTime
        updateCurrentLyric()
      }
    }

    onMounted(() => {
      const songId = route.params.id
      if (songId) {
        fetchSongDetail(songId)
      }

      // 定时更新时间
      timeUpdateInterval.value = setInterval(updateTime, 100)
    })

    onUnmounted(() => {
      if (timeUpdateInterval.value) {
        clearInterval(timeUpdateInterval.value)
      }
    })

    return {
      song,
      defaultCover,
      lyricsLines,
      currentLyricIndex,
      lyricsContainer,
      formatTime,
      playSong,
      addToPlaylist,
      handleCoverError
    }
  }
}
</script>

<style scoped>
.song-page {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.song-header {
  display: flex;
  margin-bottom: 30px;
  background: #f9f9f9;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.album-cover {
  width: 250px;
  height: 250px;
  border-radius: 8px;
  overflow: hidden;
  flex-shrink: 0;
  margin-right: 40px;
}

.album-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.song-info {
  flex: 1;
}

.song-name {
  font-size: 32px;
  margin: 0 0 20px 0;
  color: #333;
}

.song-singer,
.song-album,
.song-duration {
  font-size: 18px;
  margin: 15px 0;
  color: #666;
}

.song-singer {
  font-weight: bold;
  color: #333;
}

.actions {
  margin-top: 30px;
}

.actions .el-button {
  margin-right: 20px;
  padding: 12px 24px;
  font-size: 16px;
}

.lyrics-section h2 {
  font-size: 24px;
  margin-bottom: 20px;
  color: #333;
  border-bottom: 1px solid #eee;
  padding-bottom: 15px;
}

.lyrics-container {
  height: 400px;
  overflow: hidden;
  padding: 20px;
  background: #f9f9f9;
  border-radius: 12px;
  scroll-behavior: smooth;
  position: relative;
}

.lyrics-content {
  transition: transform 0.3s ease-out;
  will-change: transform;
}

.lyrics-line {
  padding: 8px 0;
  text-align: center;
  font-size: 18px;
  color: #666;
  transition: all 0.3s ease;
  height: 32px;
  line-height: 32px;
}

.lyrics-line.active {
  color: #409eff;
  font-weight: bold;
  font-size: 20px;
}
</style>
